// pages/videoDetail/videoDetail.js
var app = getApp();
var WxParse = require('../../wxParse/wxParse.js');
var api = require('../../utils/api.js')
Page({

  
  /**
   * 页面的初始数据
   */
  data: {
    controlShow:true,
    videoInfo:[],
    videoList:[],
    col1:[],
    col2:[],
    nolaud:true,
    commentList:[],
    pages:1,
    focus:false,
    addStatus:false,
    isFocus:false,
    isReply:false,
    isReplys:false,
    reply_holder:'说点什么',
    commentStr:'',//评论内容
    type:1,//回复层级 默认为1 最大为2
    v_r_id:0//回复上级id
  },
  toVideo(e) {
    let id = e.currentTarget.dataset.id;
    console.log(e)
    wx.navigateTo({
      url: '/pages/videoDetail/videoDetail?file_id='+id
    })
  },
  videoPause(e){
    if(this.data.is_free==0||this.data.is_pay==1){
      return
    }
    let time = e.detail.currentTime.toFixed(0);
      if(time >= 60){
        this.videoContext.pause();
        this.data.controlShow=false
        wx.showToast({
          title: '试看结束，请购买后再观看',
          icon: 'none',
          duration:3000
        })
    }
  },
  // 点赞
  laudtap(){
    const that = this
    // 从未登录时的点赞
    if(wx.getStorageSync('token')==''){
      let nolaud = that.data.nolaud
      let likes = that.data.likes
      if(nolaud){
        wx.showToast({
          title: '点赞成功',
          icon:'none'
        })
        that.setData({
          nolaud:false,
          likes:likes+1
        })
      }else{
        wx.showToast({
          title: '已取消点赞',
          icon:'none'
        })
        that.setData({
          nolaud:true,
          likes:likes-1
        })
      }
      
      return
    }
    // 还没点赞
    if(that.data.nolaud){
      let status = 1
      var token = wx.getStorageSync('token')
      let file_id = that.data.file_id
      wx.request({
        url: app.globalData.host+'VideoToken/up',
        method:'POST',
        data:{
          status,
          token,
          file_id
        },
        success(res){
          if(res.data.code==5001){
            wx.showToast({
              title: 'token已失效,请您重新登录',
              icon:'none'
            })
            wx.switchTab({
              url: '/pages/personal/personal',
            })
            return
          }
          wx.showToast({
            title: '点赞成功',
            icon:'none'
          })
          that.setData({
            nolaud:false,
            likes:res.data.data
          })
        },
        fail(err){
          console.log(err)
        }
      })
    }else{
      let status = 0
      var token = wx.getStorageSync('token')
      let file_id = that.data.file_id
      wx.request({
        url: app.globalData.host+'VideoToken/up',
        method:'POST',
        data:{
          status,
          token,
          file_id
        },
        success(res){
          if(res.data.code==5001){
            wx.showToast({
              title: 'token已失效,请您重新登录',
              icon:'none'
            })
            wx.switchTab({
              url: '/pages/personal/personal',
            })
            return
          }
          wx.showToast({
            title: '已取消点赞',
            icon:'none'
          })
          that.setData({
            nolaud:true,
            likes:res.data.data
          })
        },
        fail(err){
          console.log(err)
        }
      })
    }
  },
  // 分享
  toshare(){
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    })
  },
  // 通过file_id获取对应视频详情
  getVideoInfo(file_id,page){
    const that = this
    let params = {
      page,
      file_id,
      token:wx.getStorageSync('token')
    }
    wx.request({
      url: app.globalData.host+'Video/video_list',
      method:'GET',
      data:params,
      success(res){
        let videoInfo = that.data.videoInfo
        let videoInfo1 = res.data.data
        if (page == 1) {
            videoInfo = res.data.data
        } else {
          videoInfo = [...videoInfo, ...videoInfo1]
        }
        for(var index in videoInfo1){
          videoInfo[0].remark.replace('<img ', '<img style="max-width:100%;height:auto"')
          console.log(videoInfo[0].remark)
          that.setData({
            videoInfo,
            page,
            price:videoInfo1[index].price,
            pageNum:videoInfo1[index].length,
            is_free:videoInfo1[index].is_free,
            is_pay:videoInfo1[index].is_pay,
          })
        }
      },
      fail(err){
        wx.showToast({
          title: res.data.msg,
          icon:'none'
        })
      }
    })
  },
  // 调用支付接口
  goPay(){
  // 先判断是否需要付费
    if(this.data.is_free==0){
      return
    }else if(this.data.is_pay==1){
      wx.showToast({
        title: '您已经支付过了,请刷新后进行观看',
        icon:'none'
      })
      return
    }
    // 判断token
    let token = wx.getStorageSync('token')
    let type = wx.getStorageSync('type')
    console.log(type)
    if(token==''||type==undefined||type==''){
      wx.showLoading({
        title: '请登录后再支付',
      })
      setTimeout(() => {
        wx.switchTab({
          url: '/pages/personal/personal'
        })
      }, 1000)
        return
    }
    const that = this
    let params = {
      price:this.data.price,
      file_id:this.data.file_id,
      token:wx.getStorageSync('token')
    }
    wx.request({
      url: app.globalData.host+'Video/wxpay',
      data:params,
      method:'GET',
      success(res){
        if(res.data.code==2000){
          let {nonceStr,package:package1,signType,paySign,timeStamp}=res.data.data
          if(nonceStr==undefined){
            wx.showLoading({
              title: '登录后再支付',
            })
            setTimeout(() => {
              wx.switchTab({
                url: '/pages/personal/personal'
              })
            }, 1000)
            return
          }
          wx.requestPayment({
            nonceStr,
            package: package1,
            paySign,
            signType,
            timeStamp,
            success:(suc) =>{
              wx.showToast({
                title: '支付成功',
              })
              setTimeout(() => {
                wx.navigateTo({
                  url: '/pages/videoDetail/videoDetail?file_id='+that.data.file_id
                })
              }, 1000)
            },
            fail(error){
              wx.showToast({
                title: '支付失败',
                icon:'none'
              })
              setTimeout(() => {
                wx.navigateTo({
                  url: '/pages/videoDetail/videoDetail?file_id='+that.data.file_id
                })
              }, 1000)
            }
          })
        }else{
          wx.showToast({
            title: '出错了,请重新登陆',
            icon:'none'
          })
          wx.switchTab({
            url: '/pages/personal/personal',
          })
          wx.setStorageSync('back', '1')
          return
        }
      },
      fail(err){
        wx.showToast({
          title: err.errMsg,
          duration: 1500,
          icon: 'none',
          mask: true
        })
      }
    })
  },
  getVideoList(page,search){
    let params={
      token: wx.getStorageSync('token'),
      page,
      search,
      price:0.01
    }
    const that = this
    wx.request({
      url: app.globalData.host+'Video/index',
      method:'GET',
      // header:{"Accept": "*/*"},
      data:params,
      success(res){
        let videoList = that.data.videoList
        let videoList1 = res.data.data
        if (page == 1) {
          videoList = res.data.data;
        } else {
          videoList = [...videoList, ...videoList1]
        }
        let col1 = that.data.col1
        let col2 = that.data.col2
        for(var index in videoList){
          index % 2 == 0?col1.push(videoList[index]):col2.push(videoList[index])
        }
        that.setData({
          col1,
          col2,
          page,
          pageNum:videoList1.length,
        })
      },
      fail(err){
        wx.showToast({
          title: res.data.msg,
        })
      }
    })
  },
  // 输入框确认事件
  addFirstCom(isReply,isReplys,type,v_r_id){
    // 如果是回复状态
    isReply = this.data.isReply
    isReplys = this.data.isReplys
    if(isReply){
      let type = this.data.reply1_type
      let v_r_id = this.data.reply1_v_r_id
      this.addComment(type,v_r_id)
    }else if(isReplys){
      let type = this.data.reply2_type
      let v_r_id = this.data.reply2_v_r_id
      this.addComment(type,v_r_id)
    }else{
      let type = 1
      let v_r_id = 1
      this.addComment(type,v_r_id)
    }
  },
  // 添加评论
  addComment(type,v_r_id){
    if(this.data.commentStr==''){
      wx.showToast({
        title: '评论内容不能为空',
        icon:'none'
      })
      return
    }
    const that = this
    let file_id = that.data.file_id
    let content=that.data.commentStr
    let token = wx.getStorageSync('token')
    let username=that.data.userInfo.username
    let user_img=that.data.userInfo.avatarUrl
    wx.request({
      url: app.globalData.host+'Video/add_comment',
      method:'POST',
      data:{
        file_id,
        type,
        v_r_id,
        content,
        username,
        user_img,
        token,
      },
      success(res){
        that.setData({
          isFocus:false,
          isReply:false,
          isReplys:false,
          commentStr:'',
          reply_holder:'说点什么',
          addStatus:true
        })
        if(res.data.code==2000){
          wx.showToast({
            title: res.data.msg,
            icon:'none'
          })
        }else{
          wx.showToast({
            title: res.data.msg,
            icon:'none'
          })
        }
        that.getCommentList(1)
      }
    })
  },
  // 设置分享到朋友圈的标题
  onShareTimeline:function(){
    return {
      title:'智克艺术-'+this.data.videoInfo[0].school_name+'-'+this.data.videoInfo[0].filetitle,
      query:{
        file_id:this.data.file_id
      },
      imageUrl:this.data.videoInfo[0].fileimg
    }
  },
  // 回复1级评论
  reply1(e){
    console.log(e.currentTarget.dataset)
    let u_name = e.currentTarget.dataset.name==null?this.data.userInfo.nickName:e.currentTarget.dataset.name
    let type=2
    let v_r_id = e.currentTarget.dataset.id
    this.setData({
      isFocus:true,
      isReply:true,
      reply1_type:type,
      reply1_v_r_id:v_r_id,
      reply_holder:'回复@'+u_name
    })
  },
  // 回复2级评论
  reply2(e){
    let type=2
    let v_r_id = e.currentTarget.dataset.id
    let u_name = e.currentTarget.dataset.name
    this.setData({
      isFocus:true,
      isReply:false,
      isReplys:true,
      reply2_type:type,
      reply2_v_r_id:v_r_id,
      reply_holder:'回复@'+u_name
    })
  },
  // // 获取所有回复评论的条数
  // getLength(){
  //   let length1 = this.data.commentList
  // },
  // 输入/提交评论
  setStr(e){
    let val = e.detail.value
    let commentStr = this.data.commentStr
    this.setData({
      commentStr:val
    })
  },
  foucsup(){
    this.setData({
      isFocus:true,
      isReply:false,
    })
  },
  // 获取评论
  getCommentList(pages){
    const that = this
    if(that.data.addStatus){
      pages=1
      that.setData({
        pages:1
      })
    }else{
      pages = that.data.pages
    }
    let file_id = that.data.file_id
    wx.request({
      url: app.globalData.host+'Video/comment_list',
      method:'POST',
      data:{
        file_id,
        page:pages
      },
      success(res){
        let commentList = that.data.commentList
        let commentList1 = res.data.data
        if(commentList1==''){
          wx.showToast({
            title: res.data.msg,
            icon:'none'
          })
          return
        }
        if(pages==1){
          commentList = res.data.data
        }else{
          commentList = [...commentList,...commentList1]
        }
        if(commentList==''){
          that.setData({
            noComments:true
          })
        }
        for(var index in commentList1){
          var commentTime = new Date(commentList1[index].create_time*1000).dateFormat('Y年m月d日')
          commentList1[index].create_time = commentTime
        }
        if(that.data.addStatus){
          pages = that.data.pages
        }else{
          pages++
        }
        that.setData({
          commentList,
          commentStr:'',
          noComments:false,
          pages,
          addStatus:false
        })
      },
      fail(err){
        console.log(err)
      }
    })
  },
  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    
    // console.log(wx.getSystemInfoSync())
    this.setData({
      file_id : options.file_id,
      price:options.price
    })
    this.getCommentList(this.data.pages)
    wx.getUserInfo({
      success: res => {
        var userInfo = res.userInfo
        this.setData({
          userInfo
        })
      }
    })
    this.getVideoList()
    this.getVideoInfo(this.data.file_id)
    const that = this;
    let token = wx.getStorageSync('token')
    api.fetchApi('Video/video_List', { file_id: options.file_id,token}).then(res=>{
      var videoDetail=res;
      if(res[0].remark!==null){
        let remark = res[0].remark;
        res[0].remark = remark.replace(/&tp=webp/gi,'');
        WxParse.wxParse('article', 'html', remark, that, 0)
      }else{
        this.setData({
          noremark:true
        })
      }
      that.setData({
        videoDetail,
        likes:res[0].likes==null?0:res[0].likes
      })
      var formDate = new Date(that.data.videoInfo[0].create_time*1000).dateFormat('Y年m月d日')
      that.setData({
        formDate
      })
      if(that.data.videoDetail[0].video_like==1){
        that.setData({
          nolaud:false
        })
      }else{
        that.setData({
          nolaud:true
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    this.videoContext = wx.createVideoContext('myVideo'); 
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    var page = this.data.page || 1;
    this.getCommentList(this.data.pages)
    return
    wx.showLoading({
      title: '正在加载...',
    })
    setTimeout(function () {
      wx.hideLoading()
    }, 500)
    page++;
    if (this.data.pageNum < 4) {
      wx.showToast({
        title: '没有更多视频了',
        icon: 'none',
      })
      return
    }
    this.getVideoList(page);
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
    return {
      title:'智克艺术-'+this.data.videoInfo[0].school_name+'-'+this.data.videoInfo[0].filetitle,
      query:{
        file_id:this.data.file_id
      },
　　　imageUrl:this.data.videoInfo[0].fileimg
    }
  }
})